Garbage Collector is a program, provided by .net; runs in background as a low priority thread and keep track of those objects that are no longer referred by any reference by making them a “dirty objects”. The garbage collector is invoked by .net runtime at regular interval and removes the dirty object from the memory.
Before removing the object from the memory, the garbage collector call the Finalize() method or destructor of the object, so as to allow the object to free its memory.
Why Use the Garbage Collector?
- Forget to destroy the object. This would mean that the object’s destructor (if it had one) would not run and memory would not be deallocated then we could quite easily run out of memory.
- Tr try to destroy an active object. If a class held a reference to a destroyed object, it would be a dangling reference. The dangling reference would end up referring either to unused memory or possibly to a completely different object in the same piece of memory. Either way, the outcome of using a dangling reference would be undefined at best or a security risk at worst.
- Try and destroy the same object more than once. This might or might not be disastrous, depending on the code in the destructor
Forcing Garbage Collection
To force the Garbage Collector (GC) to spin through all unused objects and de-allocate them, we need to use GC.Collect method. When we call GC.Collect, the GC will run each object's finalizer on a separate thread.
Example
GC.Collect();
GC.WaitForPendingFinalizers();
GC.WaitForPendingFinalizers() synchronous method that will not return until
the GC.Collect() has finished its work.
Sushant Mishra
22-Jun-2017It was really helpful to read this post.